//
//  WallPaperVC.swift
//  HLDesktop
//
//  Created by 黄龙 on 2023/9/15.
//

import UIKit
import Photos

class WallPaperVC: UIViewController {
    lazy var collectView: UICollectionView = {
                // FlowLayout自定义设置
        let layout = UICollectionViewFlowLayout.init()
            // 设置item的排列方式 ( horizontal , vertical)
        layout.scrollDirection = .vertical
                // 设置item的size
        let backW = screen_W - 20
        let itemW = (backW-4*5) / 3
        let itemH = itemW * screen_H/screen_W
        layout.itemSize = CGSize(width:itemW , height: itemH)
//最小列间距
        layout.minimumLineSpacing = 3
//最小行间距
        layout.minimumInteritemSpacing = 3
//设置item的四边边距（四边边距不是每个item的内缩边距，而是外间隔连距，所以计算item大小时，还要将边距计算在内减掉边距后，再算item大小）
        layout.sectionInset = UIEdgeInsets.init(top: 5, left: 5, bottom: 5, right: 5)
//设置页头尺寸
        layout.headerReferenceSize = CGSize(width: backW, height: 0)

//设置页尾尺寸
        layout.footerReferenceSize = CGSize(width: backW, height: 0)
        
        // 初始化
        let collectview = UICollectionView.init(frame: CGRect(x: 0, y: 0, width: backW, height: itemH), collectionViewLayout: layout)
            // 设置背景颜色
        collectview.backgroundColor = .systemGroupedBackground
        // 设置代理对象
        collectview.delegate = self
        // 设置数据源对象
        collectview.dataSource = self
        collectview.showsVerticalScrollIndicator = false
            // 设置垂直滚动是否滚到item的最底部
        collectview.alwaysBounceVertical = true
            // 设置水平滚动是否滚到item的最右边
//        collectview.alwaysBounceHorizontal = true
            // 开启uicollectionView的分页显示效果
        collectview.isPagingEnabled = false //与scrollview的分页类似,分页滑动，还是平滑
        
        // 注册Cell
        collectview.register(WallpaperCell.self, forCellWithReuseIdentifier: "WallpaperCell")
        collectview.register(WallpaperCell.self, forCellWithReuseIdentifier: "WallpaperCell_Gif")
        // 注册Hearder
//        collectview.register(SectionHeader.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionHeader, withReuseIdentifier: "headerIdentifier")
        
        // 注册footer
//        collectview.register(UICollectionReusableView.self, forSupplementaryViewOfKind:UICollectionView.elementKindSectionFooter, withReuseIdentifier: "footIdentifier")
        
        return collectview
     }()
    
    var localPapers:[String] = []
    var paperAuthor:[String] = []
    var paperShowReview:UIView?
    private var selectWallPaperBlock:((_ paperImage:UIImage?,_ paperUrl:String?)->Void)?
    
    var forPageIndex:Int = 0
    var titleSource:[String] = []
    var schemeSource:[String] = []
    var icourlSource:[String] = []
    var storeLinkSource:[String] = []
    
    var iSegmentIndex:Int = 0
    var iPaperReviewIndex:Int=0 //预览图片index,=nil表示不是从列表图片预览，而是相册图片预览
    var iTapPaperIndex = 0 //记录是点击哪个图片打开的预览，以便关闭预览后刷新
    var currentPaperImage:UIImage? //当前预览的图片源，可以直接保存到相册
    var currentPaperUrl:String?
    
    var gifPaper1:[String]? //youdao服务
    var gifPaper2:[String]? //简书服务
    
    public var didCloseBlock:os_block_t?
    
    var superSnapshotView:UIView?
    var superSnapshotPosition:CGPoint?
    
    deinit {
        print("没有循环引用才会触发:WallPaperVC.deinit")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .systemGroupedBackground
        // Do any additional setup after loading the view.
        self.initView()

//        let swipeRight = UISwipeGestureRecognizer(target: self, action: #selector(swipeToRight(_:)))
//        swipeRight.direction = .right
//        view.addGestureRecognizer(swipeRight)
        
        if let snapView = superSnapshotView{
            snapView.frame = CGRect(x: 0, y: 0, width: screen_W, height: screen_H)
            self.view.addSubview(snapView)
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if let _ = superSnapshotView, let position = superSnapshotPosition{
            self.view.animateCircular(withDuration: 0.5, center: position) {[weak self] in
                self?.superSnapshotView?.removeFromSuperview()
                self?.superSnapshotView = nil
            }
        }
    }
    
//    @objc func swipeToRight(_ recognizer:UISwipeGestureRecognizer){
//        let point=recognizer.location(in: self.view)
////        print(point.x)//这个点是滑动的起点
//        if point.x<20{
//            self.dismiss(animated: true)
//        }
//    }
    
    func initTopBar(_ topSpace:CGFloat){
        let topView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: topSpace))
        view.addSubview(topView)
        let lineH = CALayer()
        topView.layer.addSublayer(lineH)
        lineH.frame = CGRect(x: 0, y: topSpace-0.5, width: screen_W, height: 0.5)
        lineH.backgroundColor = UIColor.systemGray.withAlphaComponent(0.5).cgColor
        
        let titleLabel = UILabel(frame: CGRect(x: 0, y: topSpace - 48, width: screen_W, height: 48))
        topView.addSubview(titleLabel)
        titleLabel.font = .boldSystemFont(ofSize: 16)
        titleLabel.text = "壁纸&屏保&锁屏"
        titleLabel.textColor = .label
        titleLabel.textAlignment = .center
        
        let closeButton = UIButton(frame: CGRect(x: screen_W-48, y: topSpace-48, width: 48, height: 48))
        topView.addSubview(closeButton)
        closeButton.setImage(UIImage(named: "toolbar_close_1@2x.png"), for: .normal)
        closeButton.addActionWithBlock { [weak self](sender) in
            Vibrations.light.vibrate()
            self?.didCloseBlock?()
            self?.didCloseBlock = nil //必须释放，才能deinit
            self?.dismiss(animated: false)
        }
    }

    func initView(){
        let topSpace = UIDevice.ui_navigationFullHeight()
        self.initTopBar(topSpace)

        let btnWidth = screen_W-60
        var iTop = topSpace+20.0
        let albumBtn = ProfileButton(frame: CGRect(x: 30, y: iTop, width: btnWidth, height: 42))
        view.addSubview(albumBtn)
        albumBtn.setTitle("  从手机相册选择", for: .normal)
        albumBtn.setImage(UIImage(named: "albumBtn@2x.png"), for: .normal)
        albumBtn.setTitleColor(prjTitleColor, for: .normal)
        albumBtn.easyRoundRect(corner: [.topLeft,.topRight], radii: CGSize(width: 6, height: 6))
        albumBtn.backgroundColor = prjTitleColor.withAlphaComponent(0.75)
        albumBtn.layer.borderColor = UIColor.white.withAlphaComponent(0.5).cgColor
        albumBtn.addActionWithBlock { [weak self](sender) in
            if let btn = sender as? ProfileButton{
                btn.animateTouchUpInside {
                    self?.showAlbumSelector()
                }
            }
        }

        iTop += 42+10
        let headHeight = 36.0
        let headview = UIView(frame: CGRect(x: 0, y: iTop, width: screen_W, height: headHeight))
        view.addSubview(headview)
        let items = ["精选壁纸","屏保壁纸","锁屏壁纸"]
        let segment = UISegmentedControl(items: items)
        headview.addSubview(segment)
        segment.frame = CGRect(x: screen_W/2 - 200/2, y: 0, width: 200, height: headHeight)
        segment.selectedSegmentIndex = iSegmentIndex
        segment.addTarget(self, action: #selector(segmentChange(_:)), for: .valueChanged)

        iTop += headHeight
        view.addSubview(self.collectView)
        collectView.frame = CGRect(x: 10, y: iTop, width: screen_W-20, height: screen_H - iTop)

        self.initDataAtPage(0)
    }
    
    func selectWallPaperForPage(_ pageIndex:Int,completion:@escaping (_ papaerImage:UIImage?,_ paperUrl:String?)->Void){
        self.forPageIndex = pageIndex
        self.selectWallPaperBlock = completion
    }
    
    @objc func segmentChange(_ segmented:UISegmentedControl) {
        Vibrations.selection.vibrate()
        iSegmentIndex = segmented.selectedSegmentIndex
        self.initDataAtPage(iSegmentIndex)
    }
    
//MARK: - 初始化壁纸
    func initDataAtPage(_ ipage:Int){
        self.localPapers.removeAll()
        self.paperAuthor.removeAll()
        var authorIndex = 0
        if 0 == ipage{
            let author = ["adong","黄龙","九溪","烟树","云栖","苏堤","春晓","南屏","霁雪","睛雨","枫桥","夕照"]
            for i in 0 ..< 132{
                let sname = String(format: "wall\(i)@2x.webp")
                localPapers.append(sname)
                paperAuthor.append(author[authorIndex])
                if (i+1) % 11 == 0{
                    authorIndex += 1
                }
            }
        }else if 1 == ipage{
//Gif
            localPapers.append("IMG_9300.webp")
            gifPaper1 = ["https://upload-images.jianshu.io/upload_images/6873388-56003ea0ff6aa181.gif"]
            gifPaper2 = ["https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCEc37ba7f5816e2c1fa471b46f9c994c63/154775"]
            
            localPapers.append("IMG_9301.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-0a044149363dea7d.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCE896e8770f9e1b7f731d1ffd99a58ac1c/154778")
            localPapers.append("IMG_9302.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-37b883290280e216.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCE84586357c30914a2d7064a1b566b29aa/154776")
            localPapers.append("IMG_9303.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-daf2e56f96e154e6.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCE5e5937d5253cf26f7ec7d97f38907c3f/154777")
            localPapers.append("IMG_9304.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-c1ee4effa9581eb1.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCE38c3c41c81826dce0344a244cc8aa730/154774")
            localPapers.append("IMG_9305.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-41f2e448890a07b2.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/f8f4d279d4db930aec6fc8576ef66ce6/xmlnote/WEBRESOURCE93f4edb40824b4af2a8c64b488043c37/154780")
            localPapers.append("IMG_9306.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-6a449b55dae9d297.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/cc7c92a5ec3542b9b564d3934469cfc9/xmlnote/WEBRESOURCE655e51c9fbe32fac419c5feb1dc81ba0/154787")
            localPapers.append("IMG_9307.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-845283023d87f4a4.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/cc7c92a5ec3542b9b564d3934469cfc9/xmlnote/WEBRESOURCEa5f9b3ed0047312db15aa6a5e3ec59b0/154786")
            localPapers.append("IMG_9308.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-a866df771587925e.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/cc7c92a5ec3542b9b564d3934469cfc9/xmlnote/WEBRESOURCEbc5159f798e7198c9896cf3419ac4e98/154785")
            localPapers.append("IMG_9309.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-ed1cd59df097de73.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/cc7c92a5ec3542b9b564d3934469cfc9/xmlnote/WEBRESOURCEcbad6559ffe774f55fd2506fedf34528/154788")
            localPapers.append("IMG_9310.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-aea11d906c690e70.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/cc7c92a5ec3542b9b564d3934469cfc9/xmlnote/WEBRESOURCEd7e2b4788be2d20caf21e5ca64a284a8/154790")
            localPapers.append("IMG_9311.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-b681b513e3132a08.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/71134e456fc8da3783c0fd38fd74d418/xmlnote/WEBRESOURCE6ec492401467b2d8f711d270b55ec28d/154795")
            localPapers.append("IMG_9312.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-64e2739df26ca466.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/71134e456fc8da3783c0fd38fd74d418/xmlnote/WEBRESOURCEb4a5c6a6793a90518f3fe9d81a6abf28/154796")
            localPapers.append("IMG_9313.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-b3eb6fec00e99a56.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/71134e456fc8da3783c0fd38fd74d418/xmlnote/WEBRESOURCE8316319dcbeb2d9643f2c86e94253139/154797")
            localPapers.append("IMG_9314.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-01e8cd1aa5f6bb07.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/71134e456fc8da3783c0fd38fd74d418/xmlnote/WEBRESOURCE4ce2a66568e113c2b4b765e493758dfd/154794")
            localPapers.append("IMG_9315.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-5d796314882e9709.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/71134e456fc8da3783c0fd38fd74d418/xmlnote/WEBRESOURCEd527b1505dd12101a4375837875a95d5/154798")
            localPapers.append("IMG_9316.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-40dafc7ad7768d25.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6e06c8156caad8d3af1dc118f742ac34/xmlnote/WEBRESOURCEa53e919d772201c60ed0caa89763b092/154804")
            localPapers.append("IMG_9317.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-4ffa1d7552e7ed55.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6e06c8156caad8d3af1dc118f742ac34/xmlnote/WEBRESOURCE5676dd69c5b1a0fc7d60f8cea8e2a477/154805")
            localPapers.append("IMG_9318.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-9ed2c55f35cc4245.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6e06c8156caad8d3af1dc118f742ac34/xmlnote/WEBRESOURCE7fc2fdbdaf3e07fb78feff8ce810d269/154803")
            localPapers.append("IMG_9319.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-6880230323bde58e.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6e06c8156caad8d3af1dc118f742ac34/xmlnote/WEBRESOURCE80540926982785f4eb55941861176d2c/154802")
            localPapers.append("IMG_9320.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-7e7aca3aca7c713b.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6e06c8156caad8d3af1dc118f742ac34/xmlnote/WEBRESOURCEf9eb8e92bac0b0742172bb67c73cb427/154801")
            
            localPapers.append("IMG_9800.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-c002b582bb29f684.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCEd07fd3b76c2bd6679555c52fb174e885/154874")
            localPapers.append("IMG_9801.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-a33f7c9b6f2b5888.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCE8024cd9cf3f2e2df01650d1b12ee5251/154899")
            localPapers.append("IMG_9802.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-e1e9f282f37334d4.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCEd7eafbf125b9f6f37f51b996397801a2/154877")
            localPapers.append("IMG_9803.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-143903d577a356c9.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCEf296d70e32fd46c1ebbb8530d6257d9c/154880")
            localPapers.append("IMG_9804.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-83ee6a12697a5a57.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCEa2d03d923cf291cc4e4c47530b18e8df/154875")
            localPapers.append("IMG_9805.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-1758e03c7905f086.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/368dc94adb37608208f59e1a2673c296/xmlnote/WEBRESOURCEbc1549b2dfa11aec29618792988a9b84/154879")
            localPapers.append("IMG_9808.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-b0b6e5dc2ddc36e2.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCE2d3709a5ccbf1dbf27c320d216698105/154889")
            localPapers.append("IMG_9809.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-4db5cffb1bf2121e.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCE8b4f8cc9915731d9640fccf729973bfb/154890")
            localPapers.append("IMG_9810.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-08aee2097b85e31e.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCEc98e1f1deb0969b49a5a7a7659fa9636/154891")
            localPapers.append("IMG_9811.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-111234e1880bb43b.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCEd04799b18818f92aa911256b557fbd68/154892")
            localPapers.append("IMG_9812.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-17a52188ae2058a8.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCEb1ed638d38ac7c3e6632fd808c9c47c6/154894")
            localPapers.append("IMG_9813.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-3c921851ca637d70.gif")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/6615431c43a25d0125428c5db29ddd2c/xmlnote/WEBRESOURCEc78ce87b5719dc7eeb10e77abda4cf4e/154895")
            localPapers.append("IMG_9814.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-bece58d28bb23d13.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/590e2786324da34a1abdbf38e84b200d/xmlnote/WEBRESOURCEf36402c8f15a3467576267d27898ff88/155254")
            localPapers.append("IMG_9815.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-ecfb56239f3cd712.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/590e2786324da34a1abdbf38e84b200d/xmlnote/WEBRESOURCEc07e5988e01508bf825b482c474752a4/155265")
            localPapers.append("IMG_9816.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-3676509b076ee397.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/1d285c39b8653b972c916eafd28db6bd/xmlnote/WEBRESOURCEfd60beec30c7992b60d33c9baa73b25e/155259")
            localPapers.append("IMG_9817.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-61bb69eb5ab2d9f1.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/1d285c39b8653b972c916eafd28db6bd/xmlnote/WEBRESOURCE0eda4f6a64c0f3b9a79f185a7b5a4b53/155274")
            localPapers.append("IMG_9818.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-219856b0aca9d8e0.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/590e2786324da34a1abdbf38e84b200d/xmlnote/WEBRESOURCE56a379ad93d27e99ecd8ad120085fc3a/155064")
            localPapers.append("IMG_9819.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-52ef80889024dd08.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/1d285c39b8653b972c916eafd28db6bd/xmlnote/WEBRESOURCEc7f3079630cde8dc5bdc3830d17611e8/155044")
            localPapers.append("IMG_9820.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-2f91766f8e3e33e1.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCEabc2069cde53991e851b3f7ff474282f/155283")
            localPapers.append("IMG_9821.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-fb519cb928ca2dfd.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCEde08f5fdd3ebe5634dc2c687a500acf5/155290")
            localPapers.append("IMG_9822.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-29b1ac693451ee28.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCE811c8822752b30a2d995cb32058edf1a/155288")
            localPapers.append("IMG_9823.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-62b083713c2e0ce2.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCEc32b7fcefc9bb715272c6d6e432abffa/155286")
            localPapers.append("IMG_9824.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-2636a8aa5bed4cf3.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCE07ed4ea82a9411da210daddb96b354c0/155284")
            localPapers.append("IMG_9825.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-c68859b324c5f68b.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/d1c8cd9fb22d2906f5a721e08d390a08/xmlnote/WEBRESOURCEfa640017782171b92d1caa417ba14d9f/155309")
            
            localPapers.append("IMG_9770.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-f08c9e2e8386d2a8.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCE1d4a7470daa73148254fdfc2c8d6f395/155796")
            localPapers.append("IMG_9771.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-f3ec3142102f213a.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCEa16092282b1886100ebcf5db96c08b00/155797")
            localPapers.append("IMG_9772.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-3f158ec596d71771.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCEf27c2c6ad15cb2451d287d0f701cb3d1/155795")
            localPapers.append("IMG_9773.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-b7df427c95aca814.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCEd76d5a1a5598d8679322c77f9bce1efd/155794")
            localPapers.append("IMG_9774.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-b5730aa90447b2b3.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCE5b7cbada6b22bafd3abc550638ee2195/155791")
            localPapers.append("IMG_9775.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-0bac22de1d10f24c.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCEb4b5f9956333cca54a3e3b0efb0c6fc0/155792")
            localPapers.append("IMG_9776.webp")
            gifPaper1?.append("https://upload-images.jianshu.io/upload_images/6873388-ea533bae356e5324.GIF")
            gifPaper2?.append("https://note.youdao.com/yws/public/resource/af19967ad53ed7ec19246538aef94b70/xmlnote/WEBRESOURCE43c1300ec656d31e4aee59f20b8f30d3/155793")
        }
        else{
            let author = ["锁屏壁纸","爱洗澡的鱼"]
            for i in 0 ..< 24{
                let sname = String(format: "lock\(i)@2x.webp")
                localPapers.append(sname)
                paperAuthor.append(author[authorIndex])
                if (i+1) % 13 == 0{
                    authorIndex += 1
                }
            }
        }
        
        UIView.performWithoutAnimation {
//解决collectionView刷新时闪屏的bug
            self.collectView.reloadData()
        }
    }
}


extension WallPaperVC: UICollectionViewDelegate{
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        var position:CGPoint? = nil
        if let cell = collectionView.cellForItem(at: indexPath){
//获取cell在collectionView中的位置
            let rectInCollectionView = collectionView.convert(cell.frame, to: collectionView)
//获取cell相对于View的位置
            let rect = collectionView.convert(rectInCollectionView, to: collectionView.superview)
            position = CGPoint(x: rect.origin.x+rect.width/2, y: rect.origin.y+rect.height/2)
        }

        Vibrations.selection.vibrate()
        let iRow = indexPath.row
        iTapPaperIndex = iRow
        showPaperReview(iRow,position)
    }

    func collectionView(_ collectionView: UICollectionView, shouldHighlightItemAt indexPath: IndexPath) -> Bool {
        return true
    }

}

extension WallPaperVC: UICollectionViewDataSource{
        // 设置组数
        func numberOfSections(in collectionView: UICollectionView) -> Int {
            return 1
        }
    
        // 设置每组item个数
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return localPapers.count
        }
    
        // 注册cell
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            if 1 == iSegmentIndex{
                let cellString = "WallpaperCell_Gif"
                if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellString, for: indexPath) as? WallpaperCell{
                    let tmpName = localPapers[indexPath.row]
                    cell.updateGifCell(imgName: tmpName)
                    return cell
                }
            }else{
                let cellString = "WallpaperCell"
                if let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellString, for: indexPath) as? WallpaperCell{
                    let tmpName = localPapers[indexPath.row]
                    cell.updateCellImg(imgName: tmpName,And: indexPath.row < paperAuthor.count ? paperAuthor[indexPath.row] : nil)
                    return cell
                }
            }
            return UICollectionViewCell()
        }
}

extension WallPaperVC{
//MARK: - 显示预览等工具栏
    func showPaperReview(_ listIndex:Int,_ position:CGPoint?=nil){
//显示列表图片预览
        self.iPaperReviewIndex = listIndex
        
        if paperShowReview != nil{
            for perView in paperShowReview!.subviews{
                perView.removeFromSuperview()
            }
            paperShowReview?.removeFromSuperview()
            paperShowReview = nil
        }
        paperShowReview = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        view.addSubview(paperShowReview!)
        
//  利用scrollView，实现List循环展示
        let scrollView = UIScrollView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        paperShowReview?.addSubview(scrollView)
        scrollView.isPagingEnabled = true
        scrollView.isScrollEnabled = true
        scrollView.delegate = self
        scrollView.showsHorizontalScrollIndicator = false
        scrollView.tag = 1200
        
        let imagePape_0 = UIImageView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        scrollView.addSubview(imagePape_0)
        imagePape_0.contentMode = .scaleAspectFill
        imagePape_0.clipsToBounds = true
        imagePape_0.tag = 1100
        
        let imagePape_1 = UIImageView(frame: CGRect(x: screen_W, y: 0, width: screen_W, height: screen_H))
        scrollView.addSubview(imagePape_1)
        imagePape_1.contentMode = .scaleAspectFill
        imagePape_1.clipsToBounds = true
        imagePape_1.tag = 1101
        
        let imagePape_2 = UIImageView(frame: CGRect(x: screen_W*2, y: 0, width: screen_W, height: screen_H))
        scrollView.addSubview(imagePape_2)
        imagePape_2.contentMode = .scaleAspectFill
        imagePape_2.clipsToBounds = true
        imagePape_2.tag = 1102
        
        scrollView.contentSize = CGSize(width: screen_W*3, height: screen_H)
        //定位到中间图片，并显示当前壁纸
        scrollView.setContentOffset(CGPoint(x: screen_W, y: 0), animated: false)
        if 1 == self.iSegmentIndex{
//动态壁纸，从http加载,并在前页要显示加载环
//初始背景
            let bgImage_1 = UIImageView(frame: CGRect(x: screen_W, y: 0, width: screen_W, height: screen_H))
            scrollView.addSubview(bgImage_1)
            bgImage_1.contentMode = .scaleAspectFill
            bgImage_1.clipsToBounds = true
            bgImage_1.tag = 1300
//加载环
            let loading_1 = UIImageView(frame: CGRect(x: screen_W/2 - 128/2, y: screen_H/2 - 128/2, width: 128, height: 128))
            bgImage_1.addSubview(loading_1)
            loading_1.setImageWithStr(imgurl: "picLoading_ring.gif")
            
            bgImage_1.setImageWithStr(imgurl: localPapers[listIndex])
            self.currentPaperUrl = localPapers[listIndex]
            self.currentPaperImage = nil //本地Gif图片时，image为nil
            
            
            if gifPaper1 != nil && gifPaper2 != nil && gifPaper1!.count>listIndex && gifPaper2!.count>listIndex{
                func showDynamicPreviewImage(){
                    scrollView.isScrollEnabled = false
                    imagePape_1.loadImageFrom(imageurl: gifPaper1![listIndex],And:gifPaper2![listIndex]) { [weak self] picUrl in
                        bgImage_1.isHidden = true
                        scrollView.isScrollEnabled = true
                        if let weakself = self{
                            if picUrl != nil{
                                weakself.currentPaperUrl = picUrl
                            }else{
                                weakself.currentPaperUrl = nil
                            }
                            weakself.addToolbarOnReview(weakself.paperShowReview!)
                        }
                    }
                }
                if let clickPos = position{
                    self.view.animateCircular(withDuration: 0.25, center: clickPos) {
                        showDynamicPreviewImage()
                    }
                }else{
                    showDynamicPreviewImage()
                }
            }
            
            
        }else{
            func showPreviewImage(){
                imagePape_1.setImageWithStr(imgurl: localPapers[listIndex])
                self.currentPaperUrl = localPapers[listIndex]
                self.currentPaperImage = imagePape_1.image
                addToolbarOnReview(paperShowReview!)
            }
            if let clickPos = position{
                self.view.animateCircular(withDuration: 0.25, center: clickPos) {
                    showPreviewImage()
                }
            }else{
                showPreviewImage()
            }
        }
        //前一张图片
        let preIndex = 0 == listIndex ? localPapers.count-1 : listIndex-1
        imagePape_0.setImageWithStr(imgurl: localPapers[preIndex])
        //后一张图片
        let afterIndex = listIndex>=localPapers.count-1 ? 0 : listIndex+1
        imagePape_2.setImageWithStr(imgurl: localPapers[afterIndex])
    }
    

    func showAlbumPaperReview(_ paperImage:UIImage?){
//显示相册图片预览
        self.currentPaperImage = paperImage
        if paperShowReview != nil{
            for perView in paperShowReview!.subviews{
                perView.removeFromSuperview()
            }
            paperShowReview?.removeFromSuperview()
            paperShowReview = nil
        }
        paperShowReview = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        view.addSubview(paperShowReview!)
        let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        paperShowReview?.addSubview(imageView)
        imageView.contentMode = .scaleAspectFill //这样才适合不会变形
        if paperImage != nil{
            imageView.image = paperImage
        }else if let imgUrl = self.currentPaperUrl{
            imageView.setImageWithStr(imgurl: imgUrl)
        }
        addToolbarOnReview(paperShowReview!,true)
    }
    
    func addToolbarOnReview(_ spView:UIView,_ inAlbumMode:Bool = false){
//inAlbumMode=true为相册选择的图片预览
        let btnHeight = 54.0
        let toolbar = UIView(frame: CGRect(x: 0, y: screen_H-200, width: screen_W, height: btnHeight))
        spView.addSubview(toolbar)
        toolbar.backgroundColor = .black.withAlphaComponent(0.35)
        toolbar.tag = 1010
//依次放 返回\预览(叠加图标)\保存\设置\
        let btnWidth = screen_W/4.0
        let backBtn = UIButton(frame: CGRect(x: 0, y: 0, width: btnWidth, height: btnHeight))
        toolbar.addSubview(backBtn)
        backBtn.setImage(UIImage(named: "btn_white_back@2x.png"), for: .normal)
        backBtn.setTitle("返回", for: .normal)
        backBtn.setTitleColor(.white, for: .normal)
        backBtn.titleLabel?.font = .systemFont(ofSize: 11)
        backBtn.setVerticalImage(3)
        backBtn.addActionWithBlock {[weak self](sender) in
            self?.view.animateCircular(withDuration: 0.25, center: CGPoint(x: screen_W/2, y: screen_H/2),revert: true) {
                self?.closePaperReview()
            }
        }
        let reviewBtn = UIButton(frame: CGRect(x: btnWidth, y: 0, width: btnWidth, height: btnHeight))
        toolbar.addSubview(reviewBtn)
        reviewBtn.setImage(UIImage(named: "btn_white_review@2x.png"), for: .normal)
        reviewBtn.setTitle("预览", for: .normal)
        reviewBtn.setTitleColor(.white, for: .normal)
        reviewBtn.titleLabel?.font = .systemFont(ofSize: 11)
        reviewBtn.setVerticalImage(3)
        reviewBtn.addActionWithBlock {[weak self](sender) in
//显示出本页图标，并隐藏toolbar，
//任意处点击后，恢复显示
            if let weakself = self{
                toolbar.isHidden = true
                if weakself.iSegmentIndex < 2{
                    weakself.showPageprAppIco()
                }else{
                    weakself.showLockScreenState()
                }
            }
        }
        
        let downBtn = UIButton(frame: CGRect(x: btnWidth*2, y: 0, width: btnWidth, height: btnHeight))
        toolbar.addSubview(downBtn)
        if 1 == iSegmentIndex || inAlbumMode{ //相册图片无保存
            downBtn.setImage(UIImage(named: "btn_white_saver@2x.png"), for: .normal)
            downBtn.setTitle("屏保", for: .normal)
        }else{
            downBtn.setImage(UIImage(named: "btn_white_down@2x.png"), for: .normal)
            downBtn.setTitle("保存", for: .normal)
        }
        downBtn.setTitleColor(.white, for: .normal)
        downBtn.titleLabel?.font = .systemFont(ofSize: 11)
        downBtn.setVerticalImage(3)
        downBtn.addActionWithBlock { [weak self](sender) in
            if inAlbumMode {
                //相册为屏保，进一步判断相册图片是否为gif
                if let weakself = self{
                    if let albumUrl = weakself.currentPaperUrl{
                        if albumUrl == albumGifDataKey || albumUrl.lowercased().hasSuffix(".gif"){
                            weakself.alertSheetMessage("设置屏保", message: "请选择设置屏保的类型",selection_1: "设置为空闲时屏保",selection_2: "设置为充电时屏保") {
                                UserDefaults.standard.set(weakself.currentPaperUrl, forKey: "aiScreen.saver.picurl")
                                UserDefaults.standard.synchronize()
                                weakself.view.showToast("已设置为空闲屏保，Ai桌面空闲时自动生效")
                            } midBlock:{
                                UserDefaults.standard.set(weakself.currentPaperUrl, forKey: "aiScreen.saver.batteryUrl")
                                UserDefaults.standard.synchronize()
                                weakself.view.showToast("已设置为充电屏保，充电时自动生效")
                            }
                        }else{
                            weakself.view.showToast("静态图片不能设置为屏保,请选取gif图片")
                        }
                    }else{
                        weakself.view.showToast("无效图片，请重新选取！")
                    }
                }
            }else if let weakself = self{
                    if 1 == weakself.iSegmentIndex{
                    //设为屏保
                    if weakself.currentPaperUrl != nil {
                        if weakself.currentPaperUrl == weakself.localPapers[weakself.iPaperReviewIndex]{
                            weakself.view.showToast("请等待图片加载完毕!")
                        }else{
                            weakself.alertSheetMessage("设置屏保", message: "请选择设置屏保的类型",selection_1: "设置为空闲时屏保",selection_2: "设置为充电时屏保") {
                                UserDefaults.standard.set(weakself.currentPaperUrl, forKey: "aiScreen.saver.picurl")
                                UserDefaults.standard.synchronize()
                                weakself.view.showToast("已设置为空闲屏保，Ai桌面空闲时自动生效")
                            } midBlock: {
                                UserDefaults.standard.set(weakself.currentPaperUrl, forKey: "aiScreen.saver.batteryUrl")
                                UserDefaults.standard.synchronize()
                                weakself.view.showToast("已设置为充电屏保，充电时自动生效")
                            }
                        }
                    }else{
                        weakself.view.showToast("动态壁纸加载失败，请刷新加载后重试")
                    }
                }else{
                    weakself.tapAlphaBackView()
                    
                    if let picName = weakself.currentPaperUrl{
                        if picName.lowercased().hasSuffix(".webp"){//webp图片直接保存失败，需重绘，然后保存
                            let tmpImageView = UIImageView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
                            tmpImageView.image = weakself.currentPaperImage
                            if let saveImage = tmpImageView.snapshot2Image(){
                                weakself.saveImageToAlbum(saveImage)
                            }
                        }
                        else{
                            weakself.saveImageToAlbum(weakself.currentPaperImage) //webp的image直接保存会失败
                        }
                    }else{
                        weakself.saveImageToAlbum(weakself.currentPaperImage) //webp的image会失败
                    }
                    //UIImageView中的image大小是否与实际image大小是否一致？经检验：保存的图片大小是一致的！
                    weakself.closePaperReview()
                }
            }
        }
        
        
        let sureBtn = UIButton(frame: CGRect(x: btnWidth*3, y: 0, width: btnWidth, height: btnHeight))
        toolbar.addSubview(sureBtn)
        sureBtn.setImage(UIImage(named: "btn_white_sure@2x.png"), for: .normal)
        sureBtn.setTitle("设定", for: .normal)
        sureBtn.setTitleColor(.white, for: .normal)
        sureBtn.titleLabel?.font = .systemFont(ofSize: 11)
        sureBtn.setVerticalImage(3)
        sureBtn.addActionWithBlock { [weak self](sender) in
            if let self = self{
                if self.iSegmentIndex < 2{
                    if self.iSegmentIndex == 1 && !inAlbumMode{
                        //动态壁纸设定，需要确保Gif加载完毕，更新为了Gif地址
                        if self.currentPaperUrl != nil {
                            if self.currentPaperUrl == self.localPapers[self.iPaperReviewIndex]{
                                self.view.showToast("请等待图片加载完毕!")
                                return
                            }
                        }else{
                            self.view.showToast("动态壁纸加载失败，请刷新加载后重试")
                            return
                        }
                    }
                    self.tapAlphaBackView() //移除预览图标或锁定预览
                    self.closePaperReview() //移除全图预览
                    if self.setPaperToWall(){
                        self.didCloseBlock?()
                        self.dismiss(animated: false)
                    }
                }
                else{
                    self.setLockScreenPaper()
                }
            }
        }
    }
    
//MARK: 锁屏壁纸设定及教程
    func setLockScreenPaper(){
        self.alertMessage("设置锁定壁纸", message: "请确定已将该锁屏壁纸保存到相册！", okTitle: "去设置", otherTitle: "教程") {
//跳到设置壁纸
            self.tapAlphaBackView() //移除预览图标或锁定预览
            self.closePaperReview() //移除全图预览
            HLUniversalFunc.openAppScheme("App-Prefs:Wallpaper",nil)
        } midBlock: {
//显示教程：https://www.jianshu.com/p/4835efc334a9?v=1695109949522
            HLUniversalFunc.openSchemeUrl("https://note.youdao.com/s/BFfc3yay", nil)
            
//            let webVC = WebViewController()
//            self.present(webVC, animated: true)
//            webVC.loadUrlStr(urlstr: "https://note.youdao.com/s/BFfc3yay",title: "我的Ai桌面-锁屏壁纸教程")
        }
    }
    
//MARK: 显示锁屏预览效果
    func showLockScreenState(){
        let tmpAlphaView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        self.paperShowReview?.addSubview(tmpAlphaView)
        tmpAlphaView.tag = 1020
        let tapView = UITapGestureRecognizer(target: self, action: #selector(tapAlphaBackView))
        tapView.cancelsTouchesInView = false
        tapView.delaysTouchesBegan = false
        tapView.delaysTouchesEnded = false
        tmpAlphaView.addGestureRecognizer(tapView)
        
        let topSpace = UIDevice.ui_safeDistanceTop()
        let topView = UIView(frame: CGRect(x: 0, y: topSpace, width: screen_W, height: 200))
        tmpAlphaView.addSubview(topView)
//锁、时间、日期
        let suoImgView = UIImageView(image: UIImage(named: "lock_suo@2x.png"))
        topView.addSubview(suoImgView)
        var itop = 0.0
        suoImgView.frame = CGRect(x: screen_W/2 - 12, y: itop, width: 24, height: 24)
        itop += 24.0
        let dateLabel = UILabel(frame: CGRect(x: 0, y: itop, width: screen_W, height: 60))
        topView.addSubview(dateLabel)
        dateLabel.text = "9月19日周二 · 癸卯年八月初五"
        dateLabel.textColor = .secondaryLabel
        dateLabel.font = .boldSystemFont(ofSize: 16)
        dateLabel.textAlignment = .center
        itop += 60.0
        let timeLabel = UILabel(frame: CGRect(x: 0, y: itop, width: screen_W, height: 200-itop))
        topView.addSubview(timeLabel)
        timeLabel.text = "14:35"
        timeLabel.textColor = .secondaryLabel
        timeLabel.font = .boldSystemFont(ofSize: 100)
        timeLabel.textAlignment = .center
        
        let bottomView = UIView(frame: CGRect(x: 0, y: screen_H-100, width: screen_W, height: 100))
        tmpAlphaView.addSubview(bottomView)
//手电、相机
        let imgDT = UIImageView(image: UIImage(named: "lock_diantong@2x.png"))
        bottomView.addSubview(imgDT)
        imgDT.contentMode = .center
        imgDT.frame = CGRect(x: 40, y: 0, width: 50, height: 50)
        imgDT.layer.cornerRadius = 25
        imgDT.backgroundColor = .darkGray.withAlphaComponent(0.25)
        
        let imgXJ = UIImageView(image: UIImage(named: "lock_xiangjji@2x.png"))
        bottomView.addSubview(imgXJ)
        imgXJ.contentMode = .center
        imgXJ.frame = CGRect(x: screen_W-40-50, y: 0, width: 50, height: 50)
        imgXJ.layer.cornerRadius = 25
        imgXJ.backgroundColor = .lightGray.withAlphaComponent(0.45)
        
        let markView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        tmpAlphaView.addSubview(markView)
        markView.backgroundColor = .black
        markView.layer.opacity = 1
        UIView.animate(withDuration: 1.25, delay: 0, options: [.curveEaseInOut]) {
            markView.layer.opacity = 0
        }
    }
    
//MARK: 显示App图标，仿真预览
    func showPageprAppIco(){
        let tmpAlphaView = UIView(frame: CGRect(x: 0, y: 0, width: screen_W, height: screen_H))
        self.paperShowReview?.addSubview(tmpAlphaView)
        tmpAlphaView.tag = 1020
        let tapView = UITapGestureRecognizer(target: self, action: #selector(tapAlphaBackView))
        tapView.cancelsTouchesInView = false
        tapView.delaysTouchesBegan = false
        tapView.delaysTouchesEnded = false
        tmpAlphaView.addGestureRecognizer(tapView)
        
        let topSpace = UIDevice.ui_navigationFullHeight()
        let appView = UIView(frame: CGRect(x: 0, y: topSpace, width: screen_W, height: screen_H-topSpace))
        tmpAlphaView.addSubview(appView)
        
//改进版，显示当前页面、锁屏界面、主界面三个选择项.need.update
        let keyList = ["aiScreen.App.page1.data","aiScreen.App.page2.data","aiScreen.App.page3.data","aiScreen.App.page4.data","aiScreen.App.page5.data"]
        var sourceList = UserDefaults.standard.array(forKey: keyList[forPageIndex])
        let locateList = UserDefaults.standard.array(forKey: keyList[forPageIndex] + ".location")
        if sourceList == nil || sourceList?.count == 0{
            sourceList = HLUniversalFunc.getArrFromJSONFile(forName: "mostuse_apps")
        }
        titleSource.removeAll()
        icourlSource.removeAll()
        if sourceList != nil && sourceList!.count > 0{
            for perList in sourceList! {
                let tmpStr = perList as! String
                let arr = tmpStr.components(separatedBy: "&|&")
                if arr.count >= 3 { //3-5 url=xxx[&path=xx/&page=][&|&storelink=xx]&|&title=xx&|&icon=xxx
                    if 3 == arr.count{
                        let tmpTitle = (arr[1] as NSString).substring(from: 6) as String
                        titleSource.append(tmpTitle)  //title=德施曼智能
                        let tmpIco = (arr[2] as NSString).substring(from: 5) as String
                        icourlSource.append(tmpIco) //icon=https://a-1251679148.file.myqcloud.com/api/icon/ap3/mihome.png
                    }else{//4 or 5
                        let lastIndex = arr.count - 1
                        let tmpIco = (arr[lastIndex] as NSString).substring(from: 5) as String
                        icourlSource.append(tmpIco)
                        let tmpTitle = (arr[lastIndex-1] as NSString).substring(from: 6) as String
                        titleSource.append(tmpTitle)
                    }
                }
            }
        }
        
        var iTop = 0.0
        var iCol = 0
        let appWidth = 72.0
        let appHeight = 84.0
        let iJG = (screen_W - appWidth * 4.0) / 5.0 //app之前间隔
        for i in 0 ..< titleSource.count{
            var isError = true
            if locateList != nil && locateList!.count == titleSource.count{
                let pointStr = locateList![i] as! String
                let tmpArr = pointStr.components(separatedBy: "&")
                if 2 == tmpArr.count{
                    let pointX = tmpArr[0]
                    let pointY = tmpArr[1]
                    if let d_x = Double(pointX), let d_y = Double(pointY){
                        createAppIcoLabelAt(index: i, point: CGPoint(x: d_x, y: d_y),On: appView)
                        isError = false
                    }
                }
            }
            
            if isError{ //没有x，y坐标，则默认排列位置
                let locate_x = Double(iCol+1) * iJG + Double(iCol) * appWidth
                let locate_y = iTop
                createAppIcoLabelAt(index: i, point: CGPoint(x: locate_x, y: locate_y),On: appView)
            }
            
            iCol += 1
            if iCol % 4 == 0{
                iTop = iTop + appHeight + iJG
                iCol = 0
            }
        }
        
    }
 
    
    func createAppIcoLabelAt(index:Int,point:CGPoint,On backView:UIView){
        let appWidth = 72.0
        let appHeight = 84.0
        let ico_1 = IcoLabel(frame: CGRect(x: point.x, y: point.y, width: appWidth, height: appHeight))
        ico_1.setImage(imgName: icourlSource[index])
        ico_1.setTitle(title: titleSource[index])
        ico_1.didTapBlock = {
            self.tapAlphaBackView()
        }
        backView.addSubview(ico_1)
    }

    
    func closePaperReview(){
        if paperShowReview != nil{
            for perview in self.paperShowReview!.subviews{
                perview.removeFromSuperview()
            }
            self.paperShowReview?.removeFromSuperview()
            self.paperShowReview = nil
        }
        if 1 == iSegmentIndex {
//Gif因为不是设置的ImageView的image，在CollectionCell点击后，回到Collection，图像显示nil,故重新加载该Cell
            UIView.performWithoutAnimation {[weak self] in
                self?.collectView.reloadItems(at: [IndexPath(row: iTapPaperIndex, section: 0)])
            }
        }
    }
    
    @objc func tapAlphaBackView(){
        if let alphaView = self.paperShowReview?.viewWithTag(1020) as? UIView{
            for perview in alphaView.subviews{
                perview.removeFromSuperview()
            }
            alphaView.removeFromSuperview()
        }
        
        if let toolView = self.paperShowReview?.viewWithTag(1010) as? UIView{
            toolView.isHidden = false
        }
        
    }
    
}

//MARK: - 保存到相册
extension WallPaperVC{
//保存image到相册
    func saveImageToAlbum(_ image:UIImage?) {
        if image != nil{
            if let upImage = image?.fixAlbumPhotoOrientation(){
                UIImageWriteToSavedPhotosAlbum(upImage,self,#selector(saveDone),nil)
            }
        }
    }
    
    @objc func saveDone(_ image: UIImage, didFinishSavingWithError error: Error?, contextInfo: UnsafeRawPointer) {
        if error != nil{
            self.view.showToast("保存失败")
        }else{
            self.view.showToast("已保存到您的相册中")
        }
    }
}

//设定壁纸
extension WallPaperVC{
    func setPaperToWall() ->Bool{
        //self.paperShowReview?.snapshot2Image(),改用currentPaperImage，以便能使图片扩展到多屏，截屏图片不能支持多屏
        selectWallPaperBlock?(self.currentPaperImage,self.currentPaperUrl)
        return true
        
    }
    
}


//MARK: - 从相册中选择图片，并截取区域做为图标
extension WallPaperVC:UIImagePickerControllerDelegate & UINavigationControllerDelegate{
    func showAlbumSelector(){
        if UIImagePickerController.isSourceTypeAvailable(.photoLibrary) {
            PHPhotoLibrary.requestAuthorization { (status) in
                switch status {
                case .authorized: self.presentPhotoPickerController()
                case .notDetermined:
                    if status == PHAuthorizationStatus.authorized {
                        self.presentPhotoPickerController()
                    }
                case .denied:
                    let alert = UIAlertController(title: "没有权限获取照片信息", message: "照片权限已被拒绝，请开启权限后再选择照片", preferredStyle: .alert)
                    let confirmAction = UIAlertAction(title: "去设置", style: .default, handler: { (goSettingAction) in
                        DispatchQueue.main.async {
                            let url = URL(string: UIApplication.openSettingsURLString)!
                            UIApplication.shared.open(url, options: [:])
                        }
                    })
                    let cancelAction = UIAlertAction(title: "取消", style: .cancel)
                    alert.addAction(confirmAction)
                    alert.addAction(cancelAction)
                    self.present(alert, animated: true)
                case .restricted: let alert = UIAlertController(title: "权限限制", message: "照片的获取被限制了无法获取", preferredStyle: .alert)
                    let okAction = UIAlertAction(title: "好的", style: .default)
                    alert.addAction(okAction)
                    self.present(alert, animated: true)
                default: break
                }
            }
        }
        
    }
    
    func presentPhotoPickerController() {
        DispatchQueue.main.async {[weak self] in
            if let wSelf = self{
                let myPickerController = UIImagePickerController()
                myPickerController.allowsEditing = false
                myPickerController.delegate = wSelf
                myPickerController.sourceType = .photoLibrary
                myPickerController.modalPresentationStyle = .fullScreen
                wSelf.present(myPickerController, animated: true, completion: nil)
            }
        }
    }
    
    /* ----- UIImagePickerControllerDelegate ----- */
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey : Any]) {
        var imgData:UIImage?
        if let image = info[UIImagePickerController.InfoKey.editedImage] as? UIImage {
            imgData = image
//            self.albumImgView.image = image //allowsEditing = true时走这里
        } else if let image = info[UIImagePickerController.InfoKey.originalImage] as? UIImage {
            imgData = image
//            self.albumImgView.image = image//否则走这里
        }
        var imageurl = ""
        if let imgUrl = info[.imageURL] as? NSURL{
            imageurl = imgUrl.absoluteString!
//            print("\(imageurl)")
            var md5key = "aiScreen.pCache.album.jpg.\(forPageIndex)"
//            "aiScreen.pCache." + imageurl.hl_md5() //3个页面各自用只存一个Data,以免保存的Data缓存过多
            if imageurl.lowercased().hasSuffix(".gif"){//加载相册gif文件
//eg:file:///private/var/mobile/Containers/Data/Application/556ED7CA-7888-4272-AC6C-C6E05DA27E8D/tmp/CD3E3ABE-86A9-498A-AD59-27B08AF2254B.gif
//                let destUrl = URL(string: imageurl) //原来用这个也是可以的!
                if let imageSaveData = NSData(contentsOf: imgUrl as URL){
                    if imageSaveData.count > 5120000{
                        self.currentPaperUrl = imageurl
                    }else{
                        md5key = String(format: "%@.\(forPageIndex)", albumGifDataKey)
                        self.currentPaperUrl = md5key
                        UserDefaults.standard.set(imageSaveData, forKey: md5key)//当缓存>1G后，保存一个1M大小的数据都会很慢，甚至崩溃,try也没用
                        UserDefaults.standard.synchronize()
                    }
                    self.showAlbumPaperReview(nil)
                }
            }
            else if imgData != nil , let imageSaveData = imgData!.jpegData(compressionQuality: 0.2){//值比contentsOf直接读取要小很多
// compressionQuality取值0.0~1.0，值越小表示图片质量越低，图片文件自然越小，png图片则可以用imgData.pngData()转成Data
                if imageSaveData.count > 5120000{
                    self.currentPaperUrl = imageurl
                }else{
                    self.currentPaperUrl = md5key
                    UserDefaults.standard.set(imageSaveData, forKey: md5key)
                    UserDefaults.standard.synchronize()
                }
                self.showAlbumPaperReview(nil)
            }else if let imageSaveData = NSData(contentsOf: imgUrl as URL){
                if imageSaveData.count > 5120000{
                    self.currentPaperUrl = imageurl
                }else{
                    self.currentPaperUrl = md5key
                    UserDefaults.standard.set(imageSaveData, forKey: md5key)
                    UserDefaults.standard.synchronize()
                }
                self.showAlbumPaperReview(nil)
            }
        }else if let mediaURL = info[.mediaURL] as? NSURL{
            imageurl = mediaURL.absoluteString!
            print("\(imageurl)")
            self.currentPaperUrl = imageurl
            self.showAlbumPaperReview(nil)
        }
        //mediaURL:
        //file:///private/var/mobile/Containers/Data/Application/A604C48D-4565-4F9C-83E0-F5C80D11BE3D/tmp/33E083F4-3CA1-4A59-AC26-61AFD5190B9F.png
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
    
}

extension WallPaperVC:UIScrollViewDelegate{
//处理图片预览翻页操作
    func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
        func reloadPic(){
//移动结束后第2页显示当前壁纸，同时定位到第2页，这样就能接着循环往前滑看了
            if let imagePape_1 = scrollView.viewWithTag(1101) as? UIImageView{
                if 1 == iSegmentIndex{
                    self.currentPaperUrl = localPapers[iPaperReviewIndex]
                    self.currentPaperImage = nil
                    if let bgImage_1 = scrollView.viewWithTag(1300) as? UIImageView{
                        
                        bgImage_1.setImageWithStr(imgurl: localPapers[iPaperReviewIndex])
                        bgImage_1.isHidden = false
                        if gifPaper1 != nil && gifPaper2 != nil && gifPaper1!.count>iPaperReviewIndex && gifPaper2!.count>iPaperReviewIndex{
                            scrollView.isScrollEnabled = false
                            imagePape_1.loadImageFrom(imageurl: gifPaper1![iPaperReviewIndex],And:gifPaper2![iPaperReviewIndex]) { picUrl in
                                bgImage_1.isHidden = true
                                scrollView.isScrollEnabled = true
                                if picUrl != nil{
                                    self.currentPaperUrl = picUrl
                                }
                            }
                        }
                    }
                    
                }else{
                    imagePape_1.setImageWithStr(imgurl: localPapers[iPaperReviewIndex])
                    self.currentPaperUrl = localPapers[iPaperReviewIndex]
                    self.currentPaperImage = imagePape_1.image //GIF图片时currentPaperImage=nil
                }
            }
            
            scrollView.setContentOffset(CGPoint(x: screen_W, y: 0), animated: false)
//前一张图片
            if let imagePape_0 = scrollView.viewWithTag(1100) as? UIImageView{
                let preIndex = 0 == iPaperReviewIndex ? localPapers.count-1 : iPaperReviewIndex-1
                imagePape_0.setImageWithStr(imgurl: localPapers[preIndex])
            }
//后一张图片
            if let imagePape_2 = scrollView.viewWithTag(1102) as? UIImageView{
                let afterIndex = iPaperReviewIndex>=localPapers.count-1 ? 0 : iPaperReviewIndex+1
                imagePape_2.setImageWithStr(imgurl: localPapers[afterIndex])
            }
        }
        
        if scrollView is UICollectionView{
//壁纸列表collectionView的滑动，也会触发scrollViewDidEndDecelerating，需将区别
            return
        }
//        print("scrollViewDidEndDecelerating:\(scrollView.contentOffset.x)")
        if 1200 == scrollView.tag{
            let iLeft = scrollView.contentOffset.x
            if iLeft<screen_W-10{//=0
                //向前翻页,第2页的图片变到第3页，然后将第1页的图片，变更到第2页，第1页加载更前一张
                //然后仍旧定位到中间第2页，以使不断循环
                if 0 == iPaperReviewIndex{
                    iPaperReviewIndex = localPapers.count - 1
                }else{
                    iPaperReviewIndex = iPaperReviewIndex - 1
                }
                reloadPic()
            }else if iLeft>screen_W+10{ //2*screen_W
                //向后翻页，第2页图片变到第1页，第3页变到第2页，第2页加载更下一张
                //然后仍旧定位到中间第2页，以使不断循环
                if iPaperReviewIndex >= localPapers.count - 1 {
                    iPaperReviewIndex = 0
                }else{
                    iPaperReviewIndex = iPaperReviewIndex + 1
                }
                reloadPic()
            }
            //=screen_W为中间页，不需要变更处理
        }
    }
    
    func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
        if scrollView is UICollectionView{
            return
        }
//        print("scrollViewDidEndDragging:\(scrollView.contentOffset.x)")
    }
}
